<template>
  <div class="quote-container" v-loading="pageLoading" element-loading-text="加载中...">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="page-title">
        <i class="fas fa-file-invoice"></i>
        {{ pageTitle }}
        <span v-if="quoteCode" class="quote-code">{{ quoteCode }}</span>
      </div>
      <div class="page-actions">
        <el-button type="primary" @click="handleSave('draft')" :loading="saveLoading">
          <i class="fas fa-save"></i>
          保存草稿
        </el-button>
        <el-button type="success" @click="handleSave('submit')" :loading="submitLoading">
          <i class="fas fa-paper-plane"></i>
          提交报价
        </el-button>
        <el-button @click="handleCancel">
          <i class="fas fa-times"></i>
          取消
        </el-button>
      </div>
    </div>
    
    <!-- 报价基本信息 -->
    <el-card class="quote-card" shadow="never">
      <template #header>
        <div class="card-header">
          <i class="fas fa-info-circle"></i>
          报价基本信息
        </div>
      </template>
      
      <el-form 
        ref="basicFormRef" 
        :model="basicForm" 
        :rules="basicFormRules" 
        label-width="120px"
        class="basic-form"
      >
        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="客户代码" prop="customerCode">
              <el-select 
                v-model="basicForm.customerCode" 
                placeholder="请输入客户代码或名称搜索"
                style="width: 100%"
                filterable
                remote
                reserve-keyword
                :remote-method="handleCustomerSearch"
                @change="handleCustomerChange"
                :loading="customerLoading"
                clearable
              >
                <el-option 
                  v-for="customer in customerOptions" 
                  :key="customer.customerCode" 
                  :label="`${customer.customerCode} - ${customer.customerName}`"
                  :value="customer.customerCode" 
                >
                  <span style="float: left">{{ customer.customerCode }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ customer.customerName }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="业务员" prop="salesperson">
              <el-select 
                v-model="basicForm.salesperson" 
                placeholder="请输入员工代码或姓名搜索"
                style="width: 100%"
                filterable
                remote
                reserve-keyword
                :remote-method="handleEmployeeSearch"
                :loading="employeeLoading"
                clearable
              >
                <el-option 
                  v-for="employee in employeeOptions" 
                  :key="employee.employeeCode" 
                  :label="`${employee.employeeCode} - ${employee.employeeName}`"
                  :value="employee.employeeName" 
                >
                  <span style="float: left">{{ employee.employeeCode }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ employee.employeeName }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="合同编号" prop="contractNumber">
              <el-input 
                v-model="basicForm.contractNumber" 
                placeholder="请输入合同编号"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="订单日期" prop="orderDate">
              <el-date-picker
                v-model="basicForm.orderDate"
                type="date"
                placeholder="请选择订单日期"
                style="width: 100%"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="是否含税" prop="isTaxIncluded">
              <el-select 
                v-model="basicForm.isTaxIncluded" 
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option label="否" :value="0" />
                <el-option label="增值税票13%" :value="1" />
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="付款方式" prop="paymentMethod">
              <el-select 
                v-model="basicForm.paymentMethod" 
                placeholder="请选择付款方式"
                style="width: 100%"
              >
                <el-option label="现金" value="CASH" />
                <el-option label="月结30天" value="MONTHLY_30" />
                <el-option label="月结60天" value="MONTHLY_60" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- 客户信息显示区域 -->
        <div v-if="selectedCustomerInfo" class="customer-info-section">
          <el-divider content-position="left">
            <span class="divider-text">
              <i class="fas fa-building"></i>
              客户信息
            </span>
          </el-divider>
          <el-row :gutter="24" class="customer-info-row">
            <el-col :span="6">
              <div class="info-item">
                <span class="info-label">客户公司：</span>
                <span class="info-value">{{ selectedCustomerInfo.companyName }}</span>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="info-item">
                <span class="info-label">联系人：</span>
                <span class="info-value">{{ selectedCustomerInfo.contactName }}</span>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="info-item">
                <span class="info-label">联系电话：</span>
                <span class="info-value">{{ selectedCustomerInfo.contactPhone }}</span>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="info-item">
                <span class="info-label">联系地址：</span>
                <span class="info-value">{{ selectedCustomerInfo.address }}</span>
              </div>
            </el-col>
          </el-row>
        </div>
      </el-form>
    </el-card>
    
    <!-- 信息板块1：物料基本信息 -->
    <el-card class="quote-card" shadow="never">
      <template #header>
        <div class="card-header">
          <i class="fas fa-microchip"></i>
          物料基本信息
        </div>
      </template>
      
      <div class="table-container">
        <el-table 
          :data="materialBasicList" 
          stripe
          border
          style="width: 100%"
          class="material-table"
        >
          <el-table-column prop="sequence" label="序号" width="70" align="center" fixed="left">
            <template #default="{ $index }">
              <span class="sequence-number">{{ $index + 1 }}</span>
            </template>
          </el-table-column>
          
          <el-table-column label="产品名称" width="140">
            <template #default="{ row }">
              <el-input v-model="row.productName" placeholder="产品名称" size="small" />
            </template>
          </el-table-column>
          
          <el-table-column label="物料编码" width="120">
            <template #default="{ row }">
              <el-select 
                v-model="row.materialCode" 
                placeholder="输入物料编码搜索" 
                size="small" 
                style="width: 100%"
                filterable
                remote
                reserve-keyword
                :remote-method="(query) => handleMaterialSearch(query, $index)"
                allow-create
                default-first-option
                :loading="materialLoading"
                clearable
              >
                <el-option 
                  v-for="material in materialOptions" 
                  :key="material.code" 
                  :label="material.code"
                  :value="material.code" 
                />
              </el-select>
            </template>
          </el-table-column>
          
          <el-table-column label="采购订单号" width="130">
            <template #default="{ row }">
              <el-select 
                v-model="row.purchaseOrderNumber" 
                placeholder="选择或输入" 
                size="small" 
                style="width: 100%"
                filterable
                allow-create
                default-first-option
              >
                <el-option label="PO-001" value="PO-001" />
                <el-option label="PO-002" value="PO-002" />
                <el-option label="PO-003" value="PO-003" />
              </el-select>
            </template>
          </el-table-column>
          
          <el-table-column label="层数" width="90">
            <template #default="{ row }">
              <el-select 
                v-model="row.layerCount" 
                placeholder="选择或输入" 
                size="small"
                filterable
                allow-create
                default-first-option
              >
                <el-option label="1" value="1" />
                <el-option label="2" value="2" />
                <el-option label="4" value="4" />
                <el-option label="6" value="6" />
                <el-option label="8" value="8" />
              </el-select>
            </template>
          </el-table-column>
          
          <el-table-column label="板厚(mm)" width="100">
            <template #default="{ row }">
              <el-select 
                v-model="row.boardThickness" 
                placeholder="选择或输入" 
                size="small"
                filterable
                allow-create
                default-first-option
              >
                <el-option label="0.6" value="0.6" />
                <el-option label="0.8" value="0.8" />
                <el-option label="1.0" value="1.0" />
                <el-option label="1.2" value="1.2" />
                <el-option label="1.6" value="1.6" />
                <el-option label="2.0" value="2.0" />
                <el-option label="2.5" value="2.5" />
                <el-option label="3.0" value="3.0" />
              </el-select>
            </template>
          </el-table-column>
          
          <el-table-column label="表面处理" width="110">
            <template #default="{ row }">
              <el-select 
                v-model="row.surfaceTreatment" 
                placeholder="选择或输入" 
                size="small"
                filterable
                allow-create
                default-first-option
              >
                <el-option label="有铅喷锡" value="有铅喷锡" />
                <el-option label="无铅喷锡" value="无铅喷锡" />
                <el-option label="OSP" value="OSP" />
                <el-option label="沉金" value="沉金" />
                <el-option label="镀金" value="镀金" />
              </el-select>
            </template>
          </el-table-column>
          
          <el-table-column label="阻焊" width="90">
            <template #default="{ row }">
              <el-select 
                v-model="row.solderMask" 
                placeholder="选择或输入" 
                size="small"
                filterable
                allow-create
                default-first-option
              >
                <el-option label="绿油" value="绿油" />
                <el-option label="白油" value="白油" />
                <el-option label="黑油" value="黑油" />
                <el-option label="蓝油" value="蓝油" />
                <el-option label="黄油" value="黄油" />
                <el-option label="红油" value="红油" />
              </el-select>
            </template>
          </el-table-column>
          
          <el-table-column label="字符" width="90">
            <template #default="{ row }">
              <el-select 
                v-model="row.silkscreen" 
                placeholder="选择或输入" 
                size="small"
                filterable
                allow-create
                default-first-option
              >
                <el-option label="白字" value="白字" />
                <el-option label="黑字" value="黑字" />
                <el-option label="黄字" value="黄字" />
              </el-select>
            </template>
          </el-table-column>
          
          <el-table-column label="板材" width="90">
            <template #default="{ row }">
              <el-select 
                v-model="row.baseMaterial" 
                placeholder="选择或输入" 
                size="small"
                filterable
                allow-create
                default-first-option
              >
                <el-option label="FR-4" value="FR-4" />
                <el-option label="铝基板" value="铝基板" />
                <el-option label="陶瓷板" value="陶瓷板" />
              </el-select>
            </template>
          </el-table-column>
          
          <el-table-column label="交货尺寸" width="110">
            <template #default="{ row }">
              <el-input v-model="row.deliverySize" placeholder="尺寸(mm)" size="small" />
            </template>
          </el-table-column>
          
          <el-table-column label="拼版" width="90">
            <template #default="{ row }">
              <el-input v-model="row.panelization" placeholder="拼版" size="small" />
            </template>
          </el-table-column>
          
          <el-table-column label="内铜" width="90">
            <template #default="{ row }">
              <el-select 
                v-model="row.innerCopper" 
                placeholder="选择或输入" 
                size="small"
                filterable
                allow-create
                default-first-option
              >
                <el-option label="0.5oz" value="0.5oz" />
                <el-option label="1oz" value="1oz" />
                <el-option label="1.5oz" value="1.5oz" />
                <el-option label="2oz" value="2oz" />
              </el-select>
            </template>
          </el-table-column>
          
          <el-table-column label="外铜" width="90">
            <template #default="{ row }">
              <el-select 
                v-model="row.outerCopper" 
                placeholder="选择或输入" 
                size="small"
                filterable
                allow-create
                default-first-option
              >
                <el-option label="0.5oz" value="0.5oz" />
                <el-option label="1oz" value="1oz" />
                <el-option label="1.5oz" value="1.5oz" />
                <el-option label="2oz" value="2oz" />
                <el-option label="3oz" value="3oz" />
              </el-select>
            </template>
          </el-table-column>
          
          <el-table-column label="过孔工艺" width="110">
            <template #default="{ row }">
              <el-select 
                v-model="row.viaProcess" 
                placeholder="选择或输入" 
                size="small"
                filterable
                allow-create
                default-first-option
              >
                <el-option label="过孔盖油" value="过孔盖油" />
                <el-option label="过孔塞油" value="过孔塞油" />
                <el-option label="过孔开窗" value="过孔开窗" />
                <el-option label="树脂塞油" value="树脂塞油" />
              </el-select>
            </template>
          </el-table-column>
          
          <el-table-column label="测试" width="90">
            <template #default="{ row }">
              <el-select 
                v-model="row.testing" 
                placeholder="选择或输入" 
                size="small"
                filterable
                allow-create
                default-first-option
              >
                <el-option label="飞针测试" value="飞针测试" />
                <el-option label="测试架" value="测试架" />
                <el-option label="ICT测试" value="ICT测试" />
              </el-select>
            </template>
          </el-table-column>
          
          <el-table-column label="测试架费" width="110">
            <template #default="{ row }">
              <el-input-number 
                v-model="row.testFixtureFee" 
                placeholder="测试架费" 
                size="small" 
                :min="0" 
                :precision="2" 
                controls-position="right" 
              />
            </template>
          </el-table-column>
          
          <el-table-column label="加急" width="70">
            <template #default="{ row }">
              <el-select v-model="row.isUrgent" placeholder="选择" size="small">
                <el-option label="否" value="否" />
                <el-option label="是" value="是" />
              </el-select>
            </template>
          </el-table-column>
          
          <el-table-column label="数量" width="90">
            <template #default="{ row }">
              <el-input-number v-model="row.quantity" placeholder="数量" size="small" :min="0" controls-position="right" />
            </template>
          </el-table-column>
          
          <el-table-column label="单价" width="110">
            <template #default="{ row }">
              <el-input-number 
                v-model="row.unitPrice" 
                placeholder="单价" 
                size="small" 
                :min="0" 
                :precision="2" 
                controls-position="right" 
              />
            </template>
          </el-table-column>
          
          <el-table-column label="样板费" width="100">
            <template #default="{ row }">
              <el-input-number v-model="row.sampleFee" placeholder="样板费" size="small" :min="0" :precision="2" controls-position="right" />
            </template>
          </el-table-column>
          
          <el-table-column label="合计金额" width="110">
            <template #default="{ row }">
              <el-input-number v-model="row.totalAmount" placeholder="合计金额" size="small" :min="0" :precision="2" controls-position="right" />
            </template>
          </el-table-column>
          
          <el-table-column label="出货日期" width="130">
            <template #default="{ row }">
              <el-date-picker
                v-model="row.deliveryDate"
                type="date"
                placeholder="出货日期"
                size="small"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </template>
          </el-table-column>
          
          <el-table-column label="备注" width="150">
            <template #default="{ row }">
              <el-input v-model="row.remark" placeholder="备注" size="small" />
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <div class="table-actions">
        <el-button type="danger" @click="clearTableData('basic')" size="small">
          <i class="fas fa-trash"></i>
          清除数据
        </el-button>
        <el-button type="primary" @click="addTableRow('basic')" size="small">
          <i class="fas fa-plus"></i>
          新增
        </el-button>
      </div>
    </el-card>
    
    <!-- 信息板块2：尺寸和价格信息 -->
    <el-card class="quote-card" shadow="never">
      <template #header>
        <div class="card-header">
          <i class="fas fa-calculator"></i>
          尺寸和价格信息
        </div>
      </template>
      
      <div class="table-container">
        <el-table 
          :data="materialPriceList" 
          stripe
          border
          style="width: 100%"
          class="material-table"
        >
          <el-table-column prop="sequence" label="序号" width="70" align="center" fixed="left">
            <template #default="{ $index }">
              <span class="sequence-number">{{ $index + 1 }}</span>
            </template>
          </el-table-column>
          
          <el-table-column label="宽(mm)" width="100">
            <template #default="{ row }">
              <el-input-number v-model="row.widthMm" placeholder="宽度" size="small" :min="0" :precision="2" controls-position="right" />
            </template>
          </el-table-column>
          
          <el-table-column label="长(mm)" width="100">
            <template #default="{ row }">
              <el-input-number v-model="row.lengthMm" placeholder="长度" size="small" :min="0" :precision="2" controls-position="right" />
            </template>
          </el-table-column>
          
          <el-table-column label="数量" width="90">
            <template #default="{ row }">
              <el-input-number v-model="row.dimensionQuantity" placeholder="数量" size="small" :min="0" controls-position="right" />
            </template>
          </el-table-column>
          
          <el-table-column label="订单面积(mm²)" width="140">
            <template #default="{ row }">
              <el-input-number v-model="row.orderAreaMm" placeholder="面积" size="small" :min="0" :precision="2" controls-position="right" />
            </template>
          </el-table-column>
          
          <el-table-column label="平米价(元)" width="120">
            <template #default="{ row }">
              <el-input-number v-model="row.pricePerSqm" placeholder="平米价" size="small" :min="0" :precision="2" controls-position="right" />
            </template>
          </el-table-column>
          
          <el-table-column label="未税单价(元)" width="130">
            <template #default="{ row }">
              <el-input-number v-model="row.untaxedUnitPrice" placeholder="未税单价" size="small" :min="0" :precision="2" controls-position="right" />
            </template>
          </el-table-column>
          
          <el-table-column label="未税金额" width="120">
            <template #default="{ row }">
              <el-input-number v-model="row.untaxedAmount" placeholder="未税金额" size="small" :min="0" :precision="2" controls-position="right" />
            </template>
          </el-table-column>
          
          <el-table-column label="测试架费用" width="120">
            <template #default="{ row }">
              <el-input-number v-model="row.testFixtureCost" placeholder="测试架费" size="small" :min="0" :precision="2" controls-position="right" />
            </template>
          </el-table-column>
          
          <el-table-column label="未税总金额" width="130">
            <template #default="{ row }">
              <el-input-number v-model="row.untaxedTotalAmount" placeholder="未税总金额" size="small" :min="0" :precision="2" controls-position="right" />
            </template>
          </el-table-column>
          
          <el-table-column label="含税总金额" width="130">
            <template #default="{ row }">
              <el-input-number v-model="row.taxedTotalAmount" placeholder="含税总金额" size="small" :min="0" :precision="2" controls-position="right" />
            </template>
          </el-table-column>
          
          <el-table-column label="含税单价" width="120">
            <template #default="{ row }">
              <el-input-number v-model="row.taxedUnitPrice" placeholder="含税单价" size="small" :min="0" :precision="2" controls-position="right" />
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <div class="table-actions">
        <el-button type="danger" @click="clearTableData('price')" size="small">
          <i class="fas fa-trash"></i>
          清除数据
        </el-button>
        <el-button type="primary" @click="addTableRow('price')" size="small">
          <i class="fas fa-plus"></i>
          新增
        </el-button>
      </div>
    </el-card>
    
    <!-- 信息板块3：费用明细 -->
    <el-card class="quote-card" shadow="never">
      <template #header>
        <div class="card-header">
          <i class="fas fa-money-bill-wave"></i>
          费用明细
        </div>
      </template>
      
      <div class="table-container">
        <el-table 
          :data="materialCostList" 
          stripe
          border
          style="width: 100%"
          class="material-table"
        >
          <el-table-column prop="sequence" label="序号" width="70" align="center" fixed="left">
            <template #default="{ $index }">
              <span class="sequence-number">{{ $index + 1 }}</span>
            </template>
          </el-table-column>
          
          <el-table-column label="板厚板材起步价" width="150">
            <template #default="{ row }">
              <el-input-number v-model="row.basePrice" placeholder="起步价" size="small" :min="0" :precision="2" controls-position="right" />
            </template>
          </el-table-column>
          
          <el-table-column label="阻燃费" width="100">
            <template #default="{ row }">
              <el-input-number v-model="row.flameRetardantFee" placeholder="阻燃费" size="small" :min="0" :precision="2" controls-position="right" />
            </template>
          </el-table-column>
          
          <el-table-column label="沉铜费" width="100">
            <template #default="{ row }">
              <el-input-number v-model="row.copperPlatingFee" placeholder="沉铜费" size="small" :min="0" :precision="2" controls-position="right" />
            </template>
          </el-table-column>
          
          <el-table-column label="表面处理费" width="120">
            <template #default="{ row }">
              <el-input-number v-model="row.surfaceTreatmentFee" placeholder="表面处理费" size="small" :min="0" :precision="2" controls-position="right" />
            </template>
          </el-table-column>
          
          <el-table-column label="工程费" width="100">
            <template #default="{ row }">
              <el-input-number v-model="row.engineeringFee" placeholder="工程费" size="small" :min="0" :precision="2" controls-position="right" />
            </template>
          </el-table-column>
          
          <el-table-column label="运费" width="90">
            <template #default="{ row }">
              <el-input-number v-model="row.shippingFee" placeholder="运费" size="small" :min="0" :precision="2" controls-position="right" />
            </template>
          </el-table-column>
          
          <el-table-column label="铜厚费" width="100">
            <template #default="{ row }">
              <el-input-number v-model="row.copperThicknessFee" placeholder="铜厚费" size="small" :min="0" :precision="2" controls-position="right" />
            </template>
          </el-table-column>
          
          <el-table-column label="超孔费" width="100">
            <template #default="{ row }">
              <el-input-number v-model="row.extraHoleFee" placeholder="超孔费" size="small" :min="0" :precision="2" controls-position="right" />
            </template>
          </el-table-column>
          
          <el-table-column label="阻抗费" width="100">
            <template #default="{ row }">
              <el-input-number v-model="row.impedanceFee" placeholder="阻抗费" size="small" :min="0" :precision="2" controls-position="right" />
            </template>
          </el-table-column>
          
          <el-table-column label="半孔费" width="100">
            <template #default="{ row }">
              <el-input-number v-model="row.halfHoleFee" placeholder="半孔费" size="small" :min="0" :precision="2" controls-position="right" />
            </template>
          </el-table-column>
          
          <el-table-column label="合拼费" width="100">
            <template #default="{ row }">
              <el-input-number v-model="row.panelFee" placeholder="合拼费" size="small" :min="0" :precision="2" controls-position="right" />
            </template>
          </el-table-column>
          
          <el-table-column label="树脂塞孔费" width="130">
            <template #default="{ row }">
              <el-input-number v-model="row.resinPlugFee" placeholder="塞孔费" size="small" :min="0" :precision="2" controls-position="right" />
            </template>
          </el-table-column>
          
          <el-table-column label="金手指费" width="120">
            <template #default="{ row }">
              <el-input-number v-model="row.goldFingerFee" placeholder="金手指费" size="small" :min="0" :precision="2" controls-position="right" />
            </template>
          </el-table-column>
          
          <el-table-column label="合计" width="120" fixed="right">
            <template #default="{ row }">
              <div class="cost-total">
                <el-input-number 
                  v-model="row.costTotal" 
                  placeholder="费用合计" 
                  size="small" 
                  :min="0" 
                  :precision="2" 
                  controls-position="right"
                  class="total-input"
                />
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <div class="table-actions">
        <el-button type="danger" @click="clearTableData('cost')" size="small">
          <i class="fas fa-trash"></i>
          清除数据
        </el-button>
        <el-button type="primary" @click="addTableRow('cost')" size="small">
          <i class="fas fa-plus"></i>
          新增
        </el-button>
      </div>
    </el-card>
    
    <!-- 页面底部操作按钮 -->
    <el-card class="quote-card actions-card" shadow="never">
      <div class="bottom-actions">
        <div class="action-group">
          <el-button type="info" @click="handleView" size="default">
            <i class="fas fa-eye"></i>
            查看
          </el-button>
          <el-button type="warning" @click="handleGenerateContract" size="default">
            <i class="fas fa-file-contract"></i>
            生成合同
          </el-button>
          <el-button type="danger" @click="handleGeneratePDF" :loading="pdfLoading" size="default">
            <i class="fas fa-file-pdf"></i>
            生成PDF
          </el-button>
          <el-button type="success" @click="handleFinalSave" :loading="finalSaveLoading" size="default">
            <i class="fas fa-check"></i>
            保存
          </el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
import { 
  createQuote, 
  updateQuote, 
  getQuoteDetail, 
  submitQuote, 
  generateQuoteCode,
  getCustomerOptions,
  getCustomerByCode,
  getEmployeeOptions,
  searchCustomers,
  searchEmployees,
  getMaterialOptions
} from '@/api/quote'

const router = useRouter()
const route = useRoute()

// 当前操作模式（create: 新增, edit: 编辑, view: 查看）
const mode = ref('create')
const quoteId = ref(null)

// 加载状态
const pageLoading = ref(false)
const saveLoading = ref(false)
const submitLoading = ref(false)
const pdfLoading = ref(false)
const finalSaveLoading = ref(false)

// 表单引用
const basicFormRef = ref()

// 选中的客户信息
const selectedCustomerInfo = ref(null)

// 报价单编号
const quoteCode = ref('')

// 基本信息表单
const basicForm = reactive({
  customerCode: '',
  customerName: '',
  salesperson: '',
  contractNumber: '',
  orderDate: '',
  isTaxIncluded: 0,
  paymentMethod: 'CASH',
  remark: ''
})

// 基本信息表单验证规则
const basicFormRules = reactive({
  customerCode: [
    { required: true, message: '请选择客户代码', trigger: 'change' }
  ],
  salesperson: [
    { required: true, message: '请选择业务员', trigger: 'change' }
  ],
  orderDate: [
    { required: true, message: '请选择订单日期', trigger: 'change' }
  ]
})

// 选项数据
const customerOptions = ref([])
const employeeOptions = ref([])
const materialOptions = ref([])

// 搜索状态
const customerLoading = ref(false)
const employeeLoading = ref(false)
const materialLoading = ref(false)

// 页面标题计算属性
const pageTitle = computed(() => {
  switch (mode.value) {
    case 'create':
      return '新增报价单'
    case 'edit':
      return '编辑报价单'
    case 'view':
      return '查看报价单'
    default:
      return '报价单'
  }
})

// 物料信息列表
const materialBasicList = ref([
  {
    productName: '',
    materialCode: '',
    purchaseOrderNumber: '',
    layerCount: '',
    boardThickness: '',
    surfaceTreatment: '',
    solderMask: '',
    silkscreen: '',
    baseMaterial: '',
    deliverySize: '',
    panelization: '',
    innerCopper: '',
    outerCopper: '',
    viaProcess: '',
    testing: '',
    testFixtureFee: null,
    isUrgent: '否',
    quantity: null,
    unitPrice: null,
    sampleFee: null,
    totalAmount: null,
    deliveryDate: '',
    remark: ''
  }
])

const materialPriceList = ref([
  {
    widthMm: null,
    lengthMm: null,
    dimensionQuantity: null,
    orderAreaMm: null,
    pricePerSqm: null,
    untaxedUnitPrice: null,
    untaxedAmount: null,
    testFixtureCost: null,
    untaxedTotalAmount: null,
    taxedTotalAmount: null,
    taxedUnitPrice: null
  }
])

const materialCostList = ref([
  {
    basePrice: null,
    flameRetardantFee: null,
    copperPlatingFee: null,
    surfaceTreatmentFee: null,
    engineeringFee: null,
    shippingFee: null,
    copperThicknessFee: null,
    extraHoleFee: null,
    impedanceFee: null,
    halfHoleFee: null,
    panelFee: null,
    resinPlugFee: null,
    goldFingerFee: null,
    costTotal: null
  }
])

// 客户搜索方法
const handleCustomerSearch = async (query) => {
  if (!query || query.trim() === '') {
    await loadCustomerOptions()
    return
  }
  
  customerLoading.value = true
  try {
    const response = await searchCustomers(query.trim())
    if (response.code === 200 && response.data) {
      if (response.data.records) {
        customerOptions.value = response.data.records.map(item => ({
          customerCode: item.customerCode,
          customerName: item.customerName,
          companyName: item.companyName,
          contactPhone: item.contactPhone,
          companyAddress: item.companyAddress
        }))
      } else if (Array.isArray(response.data)) {
        customerOptions.value = response.data.map(item => ({
          customerCode: item.customerCode,
          customerName: item.customerName,
          companyName: item.companyName,
          contactPhone: item.contactPhone,
          companyAddress: item.companyAddress
        }))
      }
    }
  } catch (error) {
    console.error('搜索客户失败:', error)
    ElMessage.error('搜索客户失败')
  } finally {
    customerLoading.value = false
  }
}

// 员工搜索方法
const handleEmployeeSearch = async (query) => {
  if (!query || query.trim() === '') {
    await loadEmployeeOptions()
    return
  }
  
  employeeLoading.value = true
  try {
    const response = await searchEmployees(query.trim())
    if (response.code === 200 && response.data) {
      if (response.data.records) {
        employeeOptions.value = response.data.records.map(item => ({
          employeeCode: item.employeeCode,
          employeeName: item.employeeName
        }))
      } else if (Array.isArray(response.data)) {
        employeeOptions.value = response.data.map(item => ({
          employeeCode: item.employeeCode,
          employeeName: item.employeeName
        }))
      }
    }
  } catch (error) {
    console.error('搜索员工失败:', error)
    ElMessage.error('搜索员工失败')
  } finally {
    employeeLoading.value = false
  }
}

// 物料搜索方法
const handleMaterialSearch = async (query, rowIndex) => {
  if (!query || query.trim() === '') {
    materialOptions.value = []
    return
  }
  
  materialLoading.value = true
  try {
    const response = await getMaterialOptions(query.trim())
    if (response.code === 200 && response.data) {
      if (Array.isArray(response.data)) {
        materialOptions.value = response.data.map(item => ({
          code: item.materialCode || item.code,
          name: item.materialName || item.name
        }))
      } else if (response.data.records) {
        materialOptions.value = response.data.records.map(item => ({
          code: item.materialCode || item.code,
          name: item.materialName || item.name
        }))
      }
    }
  } catch (error) {
    console.error('搜索物料失败:', error)
    // 不显示错误消息，保持用户输入体验
  } finally {
    materialLoading.value = false
  }
}

// 客户变更处理
const handleCustomerChange = async (customerCode) => {
  console.log('客户变更:', customerCode)
  
  if (!customerCode) {
    selectedCustomerInfo.value = null
    basicForm.customerName = ''
    return
  }
  
  try {
    // 调用API获取客户详情
    const response = await getCustomerByCode(customerCode)
    if (response.code === 200 && response.data) {
      const customer = response.data
      basicForm.customerName = customer.customerName
      selectedCustomerInfo.value = {
        companyName: customer.companyName,
        contactName: customer.customerName, // 这里可能需要调整字段映射
        contactPhone: customer.contactPhone,
        address: customer.companyAddress
      }
    }
  } catch (error) {
    console.error('获取客户信息失败:', error)
    ElMessage.error('获取客户信息失败')
    // 查找本地选项作为备选
    const customer = customerOptions.value.find(c => c.customerCode === customerCode)
    if (customer) {
      basicForm.customerName = customer.customerName
      selectedCustomerInfo.value = {
        companyName: customer.companyName || customer.customerName,
        contactName: customer.customerName,
        contactPhone: customer.contactPhone || '',
        address: customer.companyAddress || ''
      }
    }
  }
}

// 添加表格行
const addTableRow = (type) => {
  if (type === 'basic') {
    materialBasicList.value.push({
      productName: '',
      materialCode: '',
      purchaseOrderNumber: '',
      layerCount: '',
      boardThickness: '',
      surfaceTreatment: '',
      solderMask: '',
      silkscreen: '',
      baseMaterial: '',
      deliverySize: '',
      panelization: '',
      innerCopper: '',
      outerCopper: '',
      viaProcess: '',
      testing: '',
      testFixtureFee: null,
      isUrgent: '否',
      quantity: null,
      unitPrice: null,
      sampleFee: null,
      totalAmount: null,
      deliveryDate: '',
      remark: ''
    })
  } else if (type === 'price') {
    materialPriceList.value.push({
      widthMm: null,
      lengthMm: null,
      dimensionQuantity: null,
      orderAreaMm: null,
      pricePerSqm: null,
      untaxedUnitPrice: null,
      untaxedAmount: null,
      testFixtureCost: null,
      untaxedTotalAmount: null,
      taxedTotalAmount: null,
      taxedUnitPrice: null
    })
  } else if (type === 'cost') {
    materialCostList.value.push({
      basePrice: null,
      flameRetardantFee: null,
      copperPlatingFee: null,
      surfaceTreatmentFee: null,
      engineeringFee: null,
      shippingFee: null,
      copperThicknessFee: null,
      extraHoleFee: null,
      impedanceFee: null,
      halfHoleFee: null,
      panelFee: null,
      resinPlugFee: null,
      goldFingerFee: null,
      costTotal: null
    })
  }
}

// 清除表格数据
const clearTableData = async (type) => {
  try {
    await ElMessageBox.confirm(
      '确定要清除当前板块的所有数据吗？此操作不可撤销。',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    if (type === 'basic') {
      materialBasicList.value = []
      addTableRow('basic')
    } else if (type === 'price') {
      materialPriceList.value = []
      addTableRow('price')
    } else if (type === 'cost') {
      materialCostList.value = []
      addTableRow('cost')
    }
    
    ElMessage.success('数据已清除')
  } catch {
    // 用户取消操作
  }
}

// 保存处理
const handleSave = async (type) => {
  try {
    // 验证基本信息表单
    await basicFormRef.value.validate()
    
    // 准备提交数据
    const submitData = {
      customerCode: basicForm.customerCode,
      customerName: basicForm.customerName,
      salesperson: basicForm.salesperson,
      contractNumber: basicForm.contractNumber,
      orderDate: basicForm.orderDate,
      isTaxIncluded: basicForm.isTaxIncluded,
      paymentMethod: basicForm.paymentMethod,
      remark: basicForm.remark,
      items: formatItemsData()
    }
    
    if (type === 'draft') {
      saveLoading.value = true
      try {
        let response
        if (mode.value === 'create') {
          response = await createQuote(submitData)
        } else {
          response = await updateQuote(quoteId.value, submitData)
        }
        
        if (response.code === 200) {
          ElMessage.success('草稿保存成功')
          if (mode.value === 'create') {
            // 切换到编辑模式
            mode.value = 'edit'
            quoteId.value = response.data.id
            quoteCode.value = response.data.quoteCode
            // 更新浏览器URL但不刷新页面
            window.history.replaceState({}, '', `/order/quote/edit/${response.data.id}`)
          }
        } else {
          ElMessage.error(response.message || '保存失败')
        }
      } catch (error) {
        console.error('保存失败:', error)
        ElMessage.error('保存失败，请稍后重试')
      } finally {
        saveLoading.value = false
      }
    } else if (type === 'submit') {
      submitLoading.value = true
      try {
        let response
        if (mode.value === 'create') {
          // 先创建再提交
          response = await createQuote(submitData)
          if (response.code === 200) {
            const submitResponse = await submitQuote(response.data.id, '报价单提交')
            if (submitResponse.code === 200) {
              ElMessage.success('报价单提交成功')
              router.push('/order/quote-record')
            } else {
              ElMessage.error(submitResponse.message || '提交失败')
            }
          }
        } else {
          // 先更新再提交
          response = await updateQuote(quoteId.value, submitData)
          if (response.code === 200) {
            const submitResponse = await submitQuote(quoteId.value, '报价单提交')
            if (submitResponse.code === 200) {
              ElMessage.success('报价单提交成功')
              router.push('/order/quote-record')
            } else {
              ElMessage.error(submitResponse.message || '提交失败')
            }
          }
        }
      } catch (error) {
        console.error('提交失败:', error)
        ElMessage.error('提交失败，请稍后重试')
      } finally {
        submitLoading.value = false
      }
    }
  } catch (error) {
    ElMessage.error('请检查必填字段')
  }
}

// 取消处理
const handleCancel = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要取消吗？未保存的数据将丢失。',
      '确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    router.push('/order/quote')
  } catch {
    // 用户取消操作
  }
}

// 新增的操作处理函数
const handleView = () => {
  ElMessage.info('查看功能开发中...')
  // TODO: 实现查看预览功能
}

const handleGenerateContract = () => {
  ElMessage.info('生成合同功能开发中...')
  // TODO: 实现生成合同功能
}

const handleGeneratePDF = async () => {
  pdfLoading.value = true
  try {
    // TODO: 调用生成PDF的API
    setTimeout(() => {
      pdfLoading.value = false
      ElMessage.success('PDF生成成功')
    }, 2000)
  } catch (error) {
    pdfLoading.value = false
    ElMessage.error('PDF生成失败')
  }
}

const handleFinalSave = async () => {
  try {
    // 验证基本信息表单
    await basicFormRef.value.validate()
    
    finalSaveLoading.value = true
    // TODO: 调用最终保存API
    setTimeout(() => {
      finalSaveLoading.value = false
      ElMessage.success('报价单保存成功')
    }, 1000)
  } catch (error) {
    ElMessage.error('请检查必填字段')
  }
}

// 格式化物料数据
const formatItemsData = () => {
  const items = []
  
  // 处理每一行数据，将三个表格的数据合并
  const maxLength = Math.max(
    materialBasicList.value.length,
    materialPriceList.value.length,
    materialCostList.value.length
  )
  
  for (let i = 0; i < maxLength; i++) {
    const basicItem = materialBasicList.value[i] || {}
    const priceItem = materialPriceList.value[i] || {}
    const costItem = materialCostList.value[i] || {}
    
    // 合并数据
    const item = {
      itemSequence: i + 1,
      // 物料基本信息
      productName: basicItem.productName || null,
      materialCode: basicItem.materialCode || null,
      purchaseOrderNumber: basicItem.purchaseOrderNumber || null,
      layerCount: basicItem.layerCount || null,
      boardThickness: basicItem.boardThickness || null,
      surfaceTreatment: basicItem.surfaceTreatment || null,
      solderMask: basicItem.solderMask || null,
      silkscreen: basicItem.silkscreen || null,
      baseMaterial: basicItem.baseMaterial || null,
      deliverySize: basicItem.deliverySize || null,
      panelization: basicItem.panelization || null,
      innerCopper: basicItem.innerCopper || null,
      outerCopper: basicItem.outerCopper || null,
      viaProcess: basicItem.viaProcess || null,
      testing: basicItem.testing || null,
      testFixtureFee: basicItem.testFixtureFee || null,
      isUrgent: basicItem.isUrgent || '否',
      quantity: basicItem.quantity || null,
      unitPrice: basicItem.unitPrice || null,
      sampleFee: basicItem.sampleFee || null,
      totalAmount: basicItem.totalAmount || null,
      deliveryDate: basicItem.deliveryDate || null,
      itemRemark: basicItem.remark || null,
      
      // 尺寸和价格信息
      widthMm: priceItem.widthMm || null,
      lengthMm: priceItem.lengthMm || null,
      dimensionQuantity: priceItem.dimensionQuantity || null,
      orderAreaMm: priceItem.orderAreaMm || null,
      pricePerSqm: priceItem.pricePerSqm || null,
      untaxedUnitPrice: priceItem.untaxedUnitPrice || null,
      untaxedAmount: priceItem.untaxedAmount || null,
      testFixtureCost: priceItem.testFixtureCost || null,
      untaxedTotalAmount: priceItem.untaxedTotalAmount || null,
      taxedTotalAmount: priceItem.taxedTotalAmount || null,
      taxedUnitPrice: priceItem.taxedUnitPrice || null,
      
      // 费用明细
      basePrice: costItem.basePrice || null,
      flameRetardantFee: costItem.flameRetardantFee || null,
      copperPlatingFee: costItem.copperPlatingFee || null,
      surfaceTreatmentFee: costItem.surfaceTreatmentFee || null,
      engineeringFee: costItem.engineeringFee || null,
      shippingFee: costItem.shippingFee || null,
      copperThicknessFee: costItem.copperThicknessFee || null,
      extraHoleFee: costItem.extraHoleFee || null,
      impedanceFee: costItem.impedanceFee || null,
      halfHoleFee: costItem.halfHoleFee || null,
      panelFee: costItem.panelFee || null,
      resinPlugFee: costItem.resinPlugFee || null,
      goldFingerFee: costItem.goldFingerFee || null,
      costTotal: costItem.costTotal || null
    }
    
    // 只有当行中有实际数据时才添加
    const hasData = Object.values(item).some(value => 
      value !== null && value !== '' && value !== undefined
    )
    
    if (hasData) {
      items.push(item)
    }
  }
  
  return items
}

// 加载客户选项
const loadCustomerOptions = async (keyword = '') => {
  try {
    const response = await getCustomerOptions(keyword)
    if (response.code === 200 && response.data) {
      if (response.data.records) {
        customerOptions.value = response.data.records.map(item => ({
          customerCode: item.customerCode,
          customerName: item.customerName,
          companyName: item.companyName,
          contactPhone: item.contactPhone,
          companyAddress: item.companyAddress
        }))
      } else if (Array.isArray(response.data)) {
        customerOptions.value = response.data.map(item => ({
          customerCode: item.customerCode,
          customerName: item.customerName,
          companyName: item.companyName,
          contactPhone: item.contactPhone,
          companyAddress: item.companyAddress
        }))
      }
    }
  } catch (error) {
    console.error('加载客户选项失败:', error)
  }
}

// 加载员工选项
const loadEmployeeOptions = async (keyword = '') => {
  try {
    const response = await getEmployeeOptions(keyword)
    if (response.code === 200 && response.data) {
      if (response.data.records) {
        employeeOptions.value = response.data.records.map(item => ({
          employeeCode: item.employeeCode,
          employeeName: item.employeeName
        }))
      } else if (Array.isArray(response.data)) {
        employeeOptions.value = response.data.map(item => ({
          employeeCode: item.employeeCode,
          employeeName: item.employeeName
        }))
      }
    }
  } catch (error) {
    console.error('加载员工选项失败:', error)
  }
}

// 加载基础数据
const loadBaseData = async () => {
  try {
    // 并行加载客户和员工数据
    await Promise.all([
      loadCustomerOptions(),
      loadEmployeeOptions()
    ])
  } catch (error) {
    console.error('加载基础数据失败:', error)
    ElMessage.error('加载基础数据失败')
  }
}

// 生成报价单编号
const generateCode = async () => {
  try {
    const response = await generateQuoteCode()
    if (response.code === 200) {
      quoteCode.value = response.data
    }
  } catch (error) {
    console.error('生成报价单编号失败:', error)
  }
}

// 初始化页面数据
const initPageData = async () => {
  pageLoading.value = true
  
  try {
    // 检查URL参数确定页面模式
    if (route.params.id) {
      mode.value = route.name === 'QuoteView' ? 'view' : 'edit'
      quoteId.value = parseInt(route.params.id)
      
      // 加载报价单详情
      const response = await getQuoteDetail(quoteId.value)
      if (response.code === 200 && response.data) {
        loadQuoteData(response.data)
      } else {
        ElMessage.error('报价单不存在')
        router.push('/order/quote-record')
        return
      }
    } else {
      mode.value = 'create'
      // 生成新的报价单编号
      await generateCode()
      // 设置默认订单日期为今天
      basicForm.orderDate = new Date().toISOString().substr(0, 10)
    }
    
    // 加载基础数据
    await loadBaseData()
  } catch (error) {
    console.error('初始化页面失败:', error)
    ElMessage.error('页面加载失败')
  } finally {
    pageLoading.value = false
  }
}

// 加载报价单数据到表单
const loadQuoteData = (quoteData) => {
  // 加载基本信息
  basicForm.customerCode = quoteData.customerCode
  basicForm.customerName = quoteData.customerName
  basicForm.salesperson = quoteData.salesperson
  basicForm.contractNumber = quoteData.contractNumber
  basicForm.orderDate = quoteData.orderDate
  basicForm.isTaxIncluded = quoteData.isTaxIncluded
  basicForm.paymentMethod = quoteData.paymentMethod
  basicForm.remark = quoteData.remark
  
  quoteCode.value = quoteData.quoteCode
  
  // 加载物料明细
  if (quoteData.items && quoteData.items.length > 0) {
    // 清空现有数据
    materialBasicList.value = []
    materialPriceList.value = []
    materialCostList.value = []
    
    // 分解物料数据到三个表格
    quoteData.items.forEach(item => {
      // 基本信息
      materialBasicList.value.push({
        productName: item.productName || '',
        materialCode: item.materialCode || '',
        purchaseOrderNumber: item.purchaseOrderNumber || '',
        layerCount: item.layerCount || '',
        boardThickness: item.boardThickness || '',
        surfaceTreatment: item.surfaceTreatment || '',
        solderMask: item.solderMask || '',
        silkscreen: item.silkscreen || '',
        baseMaterial: item.baseMaterial || '',
        deliverySize: item.deliverySize || '',
        panelization: item.panelization || '',
        innerCopper: item.innerCopper || '',
        outerCopper: item.outerCopper || '',
        viaProcess: item.viaProcess || '',
        testing: item.testing || '',
        testFixtureFee: item.testFixtureFee,
        isUrgent: item.isUrgent || '否',
        quantity: item.quantity,
        unitPrice: item.unitPrice,
        sampleFee: item.sampleFee,
        totalAmount: item.totalAmount,
        deliveryDate: item.deliveryDate || '',
        remark: item.itemRemark || ''
      })
      
      // 价格信息
      materialPriceList.value.push({
        widthMm: item.widthMm,
        lengthMm: item.lengthMm,
        dimensionQuantity: item.dimensionQuantity,
        orderAreaMm: item.orderAreaMm,
        pricePerSqm: item.pricePerSqm,
        untaxedUnitPrice: item.untaxedUnitPrice,
        untaxedAmount: item.untaxedAmount,
        testFixtureCost: item.testFixtureCost,
        untaxedTotalAmount: item.untaxedTotalAmount,
        taxedTotalAmount: item.taxedTotalAmount,
        taxedUnitPrice: item.taxedUnitPrice
      })
      
      // 费用明细
      materialCostList.value.push({
        basePrice: item.basePrice,
        flameRetardantFee: item.flameRetardantFee,
        copperPlatingFee: item.copperPlatingFee,
        surfaceTreatmentFee: item.surfaceTreatmentFee,
        engineeringFee: item.engineeringFee,
        shippingFee: item.shippingFee,
        copperThicknessFee: item.copperThicknessFee,
        extraHoleFee: item.extraHoleFee,
        impedanceFee: item.impedanceFee,
        halfHoleFee: item.halfHoleFee,
        panelFee: item.panelFee,
        resinPlugFee: item.resinPlugFee,
        goldFingerFee: item.goldFingerFee,
        costTotal: item.costTotal
      })
    })
  }
}

// 页面初始化
onMounted(() => {
  console.log('报价单页面已加载')
  initPageData()
})
</script>

<style scoped>
.quote-container {
  padding: 0;
  height: 100%;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: white;
  padding: 16px;
  border-radius: 6px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  border: 1px solid #ebeef5;
}

.page-title {
  font-size: 20px;
  font-weight: 600;
  color: #333;
}

.page-title i {
  margin-right: 8px;
  color: #409eff;
}

.quote-code {
  margin-left: 12px;
  padding: 4px 8px;
  background-color: #f0f9ff;
  color: #409eff;
  border: 1px solid #b3d8ff;
  border-radius: 4px;
  font-size: 14px;
  font-weight: 500;
}

.page-actions {
  display: flex;
  gap: 8px;
}

.quote-card {
  border-radius: 6px;
  flex-shrink: 0;
}

.quote-card :deep(.el-card__body) {
  padding: 16px;
}

.card-header {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  display: flex;
  align-items: center;
}

.card-header i {
  margin-right: 8px;
  color: #409eff;
}

.basic-form {
  margin-bottom: 0;
}

/* 客户信息显示区域样式 */
.customer-info-section {
  margin-top: 16px;
}

.divider-text {
  font-size: 14px;
  color: #606266;
  font-weight: 500;
}

.divider-text i {
  margin-right: 6px;
  color: #409eff;
}

.customer-info-row {
  margin-top: 12px;
}

.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.info-label {
  font-weight: 500;
  color: #606266;
  margin-right: 8px;
  white-space: nowrap;
}

.info-value {
  color: #333;
  font-weight: 500;
}

.table-container {
  margin-bottom: 16px;
  overflow-x: auto;
}

.material-table {
  border-radius: 6px;
  overflow: hidden;
}

.material-table :deep(.el-table th) {
  background-color: #fafafa;
  font-weight: 600;
  color: #333;
}

.material-table :deep(.el-table--border) {
  border: 1px solid #ebeef5;
}

.sequence-number {
  display: inline-block;
  width: 24px;
  height: 24px;
  line-height: 24px;
  background-color: #409eff;
  color: white;
  border-radius: 50%;
  font-weight: 600;
  font-size: 12px;
}

.cost-total {
  background-color: #f0f9ff;
  padding: 4px;
  border-radius: 4px;
  border-left: 3px solid #409eff;
}

.total-input :deep(.el-input-number__wrapper) {
  background-color: transparent;
  border: 1px solid #409eff;
  font-weight: 600;
}

.table-actions {
  display: flex;
  gap: 8px;
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;
}

/* 底部操作按钮样式 */
.actions-card {
  margin-top: 20px;
}

.bottom-actions {
  display: flex;
  justify-content: center;
  padding: 8px 0;
}

.action-group {
  display: flex;
  gap: 16px;
  align-items: center;
}

.action-group .el-button {
  min-width: 120px;
  height: 40px;
  font-size: 14px;
  font-weight: 500;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }
  
  .page-actions {
    justify-content: center;
    flex-wrap: wrap;
  }
  
  .basic-form :deep(.el-row) {
    margin: 0;
  }
  
  .basic-form :deep(.el-col) {
    width: 100%;
    margin-bottom: 16px;
  }
  
  .customer-info-row :deep(.el-col) {
    width: 100%;
  margin-bottom: 8px;
  }
  
  .table-actions {
    flex-direction: column;
  }
  
  .action-group {
    flex-direction: column;
    gap: 8px;
  }
  
  .action-group .el-button {
    width: 100%;
  }
}

/* 优化表格在小屏幕上的显示 */
@media (max-width: 1200px) {
  .material-table :deep(.el-table__body-wrapper) {
    overflow-x: auto;
  }
}

/* 优化按钮样式 */
.el-button {
  border-radius: 4px;
  font-weight: 500;
}

.el-button i {
  margin-right: 4px;
}

/* 优化表单样式 */
.basic-form :deep(.el-form-item) {
  margin-bottom: 16px;
}

.basic-form :deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

/* 优化输入框样式 */
.material-table :deep(.el-input__wrapper) {
  box-shadow: 0 0 0 1px #dcdfe6 inset;
}

.material-table :deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #c0c4cc inset;
}

.material-table :deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #409eff inset;
}

/* 优化选择器样式 */
.material-table :deep(.el-select .el-input__wrapper) {
  box-shadow: 0 0 0 1px #dcdfe6 inset;
}

.material-table :deep(.el-select .el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #c0c4cc inset;
}

.material-table :deep(.el-select .el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #409eff inset;
}
</style> 